<script setup lang="ts">
import { ApiDetail } from '@/api/api-manage/detail'
import axios from 'axios'
import { message } from '@/utils/message'
import { dayjs, UploadRawFile, UploadRequestOptions, UploadUserFile } from 'element-plus'
import { ApiLogBo } from '../../type'
import { addLog } from '@/api/api-manage/log'
import { generateApiLog } from '../../useApiLog'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'

const props = defineProps<{
  data: ApiDetail
}>()

const firseFileList = ref<UploadUserFile[]>([] as any)
const secondFileList = ref<UploadUserFile[]>([] as any)
const uploadRequestOptionsFirst = ref<UploadRequestOptions>(null)
const uploadRequestOptionsSecond = ref<UploadRequestOptions>(null)
const firseFaceUploadRef = ref()
const secondFaceUploadRef = ref()
const textRes = ref()
const firstFaceButtonLoading = ref(false)
const secondFaceButtonLoading = ref(false)
const doingLoading = ref(false)
const resLoading = ref(false)
const firstB64Data = ref(null)
const secondB64Data = ref(null)

/**
 * 上传文件方法
 * @param options
 */
const requestFileFirst = async (options: UploadRequestOptions) => {
  if (props.data.enabledStatus != '1') {
    message('接口已停用, 请联系管理员开启', { type: 'warning' })
    return
  }
  firseFileList.value = []
  firstFaceButtonLoading.value = true
  uploadRequestOptionsFirst.value = options
  firstFaceButtonLoading.value = false
  firseFileList.value.push({
    name: '图片1',
    status: 'success',
  })
  const reader = new FileReader()
  reader.readAsDataURL(options.file)
  reader.onload = () => {
    firstB64Data.value = reader.result
  }
  message('第一张图片上传成功', { type: 'success' })
}

const requestFileSecond = async (options: UploadRequestOptions) => {
  if (props.data.enabledStatus != '1') {
    message('接口已停用, 请联系管理员开启', { type: 'warning' })
    return
  }
  secondFileList.value = []
  secondFaceButtonLoading.value = true
  uploadRequestOptionsSecond.value = options
  secondFaceButtonLoading.value = false
  message('第二张图片上传成功', { type: 'success' })
  secondFileList.value.push({
    name: '图片2',
    status: 'success',
  })
  const reader = new FileReader()
  reader.readAsDataURL(options.file)
  reader.onload = () => {
    secondB64Data.value = reader.result
  }
}

const verifyFace = () => {
  if (props.data.enabledStatus != '1') {
    message('接口已停用, 请联系管理员开启', { type: 'warning' })
    return
  }
  if (uploadRequestOptionsFirst.value == null || uploadRequestOptionsSecond.value == null) {
    message('请先上传两张图片', { type: 'warning' })
    return
  }
  firstFaceButtonLoading.value = true
  secondFaceButtonLoading.value = true
  textRes.value = ''
  doingLoading.value = true
  resLoading.value = true
  const formData = new FormData()
  formData.append('img1', uploadRequestOptionsFirst.value.file)
  formData.append('img2', uploadRequestOptionsSecond.value.file)
  formData.append('load_weight', 'true')
  message('正在执行人脸对比识别', { type: 'info' })
  let startTime = performance.now()
  const requestTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  let res = '0'
  let resCode = 500
  axios
    .post(props.data.serverProdPath + props.data.serverUri, formData)
    .then((response) => {
      let similar: number = 0
      if (response.data?.verified == true) {
        similar = 1 - response.data.distance
        similar = similar * 100
        textRes.value = '人脸对比通过，相似度：' + similar.toFixed(2) + '%'
      } else {
        if (response.data?.distance) {
          similar = 1 - response.data.distance
        }
        textRes.value = '人脸对比不通过，相似度：' + similar.toFixed(2) + '%'
      }
      message('操作成功', { type: 'success' })
      res = '1'
      resCode = 200
    })
    .catch((err) => {
      res = '0'
      resCode = 500
      message('接口存在问题无法调用', { type: 'error' })
    })
    .finally(() => {
      let endTime = performance.now()
      let duration = endTime - startTime
      const endDateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      let userBy = '在线体验'
      if (getToken() != null && getToken() != '') {
        userBy = useUserStore().username + userBy
      }
      const log = generateApiLog(
        props.data,
        requestTime,
        endDateTime,
        duration,
        userBy,
        res,
        resCode,
        '2'
      )
      addLog(log)
      resLoading.value = false
      doingLoading.value = false
      firstFaceButtonLoading.value = false
      secondFaceButtonLoading.value = false
    })
}

const beforeUpload = (rawFile: UploadRawFile) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/jpg') {
    return true
  } else {
    message('请上传jpg图片', { type: 'warning' })
    return false
  }
}
</script>

<template>
  <br />
  <el-form>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-form-item>
          <el-upload
            ref="firseFaceUploadRef"
            action="#"
            :file-list="firseFileList"
            :show-file-list="true"
            :http-request="requestFileFirst"
            accept=".jpg, .jpeg"
            :before-upload="beforeUpload"
          >
            <el-button v-loading="firstFaceButtonLoading" type="primary"
              >上传第一张人脸图</el-button
            >
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col v-if="firstB64Data != null" :span="12">
        <el-form-item>
          <el-image :src="firstB64Data" fit="contain" style="width: 200px; height: 200px" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-form-item>
          <el-upload
            ref="secondFaceUploadRef"
            action="#"
            :file-list="secondFileList"
            :show-file-list="true"
            :http-request="requestFileSecond"
            accept=".jpg,.jpeg"
            :before-upload="beforeUpload"
          >
            <el-button v-loading="secondFaceButtonLoading" type="primary"
              >上传第二张人脸图</el-button
            >
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col v-if="secondB64Data != null" :span="12">
        <el-image :src="secondB64Data" fit="contain" style="width: 200px; height: 200px" />
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="2">
        <el-form-item>
          <el-button v-loading="doingLoading" type="primary" @click="verifyFace"
            >执行识别</el-button
          >
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item v-loading="resLoading" label="识别结果">
          <el-input v-model="textRes" type="textarea" :rows="3" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
